import util from "../../utils/util";
import answerUtil from "../../utils/answerUtil";
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isShowNumber: true,
    fullCode: '',//四位数
    randomDigit: '',//第3位或第4位数
    showNumber: false,
    gridItems: [
      { id:1,value: 1 },
      { id:2,value: 2 },
      { id:3,value: 3 },
      { id:4,value: 4 },
      { id:5,value: 5 },
      { id:6,value: 6 },
      { id:7,value: 7 },
      { id:8,value: 8 },
      { id:9,value: 9 },
      { id:0,value: 0 },
      { id:'delete',value: 'X 删除' }
    ],//键盘
    value: '',//输入框的值
    tabNum: null,
    totalCount: 0, //题目总数
    count: 0, //记录做题次数
    countdownTime: 10, // 倒计时时间
    countdownInterval: null, // 存储 interval ID
    questionIndex: 0, //当前题型索引
    questionStartTime: null,//记录题目开始时间
    answerRecords: [],//答题记录
  },
  onLoad() {
    this.generateFourDigitNumber();
    this.getTopicData();
    // 初始化时加载已有的答题记录
    const savedAnswerRecords = answerUtil.getAnswerRecords();
    this.setData({
      answerRecords: savedAnswerRecords
    });
  },
  // 获取题目数量
  getTopicData() {
    const questionIndex = wx.getStorageSync('questionInfo').questionNumber;
    const {count} = util.getData(questionIndex);
    this.setData({
      totalCount: count,
      questionIndex
    })
  },
  // 生成题目
  generateFourDigitNumber() {
    let number;
    let digits;
    // 循环生成直到第三位和第四位不同
    do {
      number = Math.floor(1000 + Math.random() * 9000); // 生成1000~9999之间的数
      digits = number.toString().split('');
    } while (digits[2] === digits[3]) // 第三位和第四位相同时继续循环

    this.setData({ 
      fullCode: number.toString(), 
      showNumber: true,
      isShowNumber:true,
      tabNum: null,
      value:'',
    });
  
    setTimeout(() => {
      this.setData({ showNumber: false }); // 隐藏四位数
      this.revealThirdOrFourth(digits);
    }, 3000); // 3秒后隐藏
    // 5秒后隐藏所有内容
    setTimeout(() => {
      this.setData({
        isShowNumber: false
      });
      // 每道题目开始倒计时
      this.startCountdown();
      this.setData({
        questionStartTime: new Date().getTime()
      })
    }, 5000);
  },
  revealThirdOrFourth(digits) {
    const pickIndex = Math.random() < 0.5 ? 2 : 3; // 2=第三位, 3=第四位
    this.setData({ randomDigit: digits[pickIndex] });
  },
  // 倒计时
  startCountdown() {
    const that = this;
    let {totalCount,count} = that.data;
    // 清除已有倒计时
    if (that.data.countdownInterval) {
      clearInterval(that.data.countdownInterval);
    }
    that.setData({
      countdownTime: 10
    });
    const interval = setInterval(() => {
      const newTime = that.data.countdownTime - 1;
      if (newTime > 0) {
        that.setData({
          countdownTime: newTime
        });
      } else {
        clearInterval(interval);
        // 倒计时结束，视为错误
        wx.showToast({
          title: '已超时',
          icon: 'none',
          duration: 1000
        });
        setTimeout(() => {
          // 使用共用方法创建并保存答题记录
          const newAnswerRecords = this.createAndSaveAnswerRecord(true);
          // 无论对错都增加总次数
          let countNum = count + 1;
          this.setData({
            count:countNum,
            answerRecords: newAnswerRecords
          })
          // 判断题目次数，跳转并打印结果
          if (countNum >= totalCount) {
            //跳转下一题
            let questionNumber = this.data.questionIndex + 1;
            const prevInfo = wx.getStorageSync('questionInfo') || {};
            wx.setStorageSync('questionInfo', {
              ...prevInfo,
              questionNumber
            });
            util.navigateByDesc(questionNumber);
          } else {
            // 继续下一题
            setTimeout(() => {
              this.generateFourDigitNumber();
            }, 1000);
          }
        }, 1000);
      }
    }, 1000);
    that.setData({
      countdownInterval: interval
    });
  },
  onTap(e) {
    const key = e.currentTarget.dataset.value;
    let currentValue = this.data.value;
    if (key === 'delete') {
      const newValue = String(currentValue).slice(0, -1);
      this.setData({
        value: newValue
      });
    } else {
      this.setData({
        value: key
      });
    }
    this.setData({
      tabNum: key
    })
  },
  onSubmit() {
    const { fullCode,totalCount } = this.data;
    let {count} = this.data;
    const randomDigit = this.data.randomDigit.toString();
    const value = this.data.value.toString();
    if (!value) return;
    const digits = fullCode.split('');
    const answerIndex = randomDigit === digits[2] ? 0 : 1;
    const correctAnswer = digits[answerIndex];
    
    let isCorrect;
    // 无论对错都增加总次数
    let countNum = count + 1;
    if (value === correctAnswer) {
      isCorrect = true
    }else{
      isCorrect = false
    }
    // 使用共用方法创建并保存答题记录
    const newAnswerRecords = this.createAndSaveAnswerRecord(false, value,isCorrect);
    this.setData({
      tabNum: null,
      count: countNum,
      answerRecords: newAnswerRecords
    })
    // 清除倒计时
    if (this.data.countdownInterval) {
      clearInterval(this.data.countdownInterval);
      this.setData({ countdownInterval: null });
    }

    if (countNum >= totalCount) {
        //跳转下一题
        let questionNumber = this.data.questionIndex + 1;
        const prevInfo = wx.getStorageSync('questionInfo') || {};
        wx.setStorageSync('questionInfo', {
          ...prevInfo,
          questionNumber
        });
        util.navigateByDesc(questionNumber);
    } else {
      this.generateFourDigitNumber(); // 下一题
    }
  },
  // 处理答题记录
  createAndSaveAnswerRecord(isTimeout = false, userOption = '',isRight = false) {
    const {questionStartTime,questionIndex} = this.data;
    const questionList = wx.getStorageSync('questionInfo').questionList;
    const currentTopic = questionList[questionIndex]
    // 计算答题时间
    const endTime = new Date().getTime();
    const answerTime = answerUtil.calculateAnswerTime(questionStartTime, endTime);

    // 判断是否正确（超时视为错误）
    let option = '';
    if (!isTimeout) {
      option = userOption;
      isRight = isRight ? 1 : 0;
    }
    
    // 创建答题记录
    const answerRecord = answerUtil.createAnswerRecord({
      qosId: 0,
      anserTime: answerTime,
      isRight: isRight,
      option: option,
      classify: currentTopic.typeCode,
      stem: '',
      accuracy: '',
      timeStemp: endTime.toString(),
      everyTxt: '',
      rightOption: '',
      score: 0,
    });
    
    // 添加答题记录
    const newAnswerRecords = answerUtil.addAnswerRecord(answerRecord);
    
    return newAnswerRecords;
  },

  onUnload() {
    // 页面卸载时确保答题记录已保存
    answerUtil.saveAnswerRecords(this.data.answerRecords);
    // 清除倒计时
    if (this.data.countdownInterval) {
      clearInterval(this.data.countdownInterval);
      this.setData({ countdownInterval: null });
    }
  }
})